package cn.yoyo.dao;

import cn.yoyo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.regex.Pattern;

@Repository
public class UserDaoImpl implements UserDao{
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public List<User> findAll() {
        return mongoTemplate.findAll(User.class);
    }

    @Override
    public User findById(String userId) {
        Query query = new Query(Criteria.where("id").is(userId));
        return mongoTemplate.findOne(query,User.class);
    }

    @Override
    public User findByUsername(String username) {
        Criteria criteria = new Criteria();
        criteria.and("username").is(username);
        Query query = new Query(criteria);
        return mongoTemplate.findOne(query,User.class);
    }

    @Override
    public void add(User user) {
        mongoTemplate.insert(user);
    }

    @Override
    public void update(User user) {
        Update update = new Update();
        Query query = new Query(Criteria.where("id").is(user.getId()));
        if (user.getNickname()!=null){
            update.set("nickname",user.getNickname());
        }
        if (user.getPhone()!=null){
            update.set("phone",user.getPhone());
        }
        if (user.getPassword()!=null){
            update.set("password",passwordEncoder.encode(user.getPassword()));
        }
        if (user.getPictureId()!=null){
            update.set("pictureId",user.getPictureId());
        }
        mongoTemplate.updateFirst(query,update,User.class);
    }

    @Override
    public void block(String userId,Integer block) {
        Update update = new Update();
        Query query = new Query(Criteria.where("id").is(userId));
        update.set("closed",block);
        mongoTemplate.updateFirst(query,update,User.class);
    }
}
